<?php

/**
 * Description of Application_Model_Fix
 *
 * @author Jean Brito
 */
abstract class Application_Model_Fix extends Application_Model_Base {

	protected $_data=array();
	protected $_autoincrement=array('id'=>0);
	public function __construct() {
		$rows=$this->_data;
		foreach($rows as $i=>$row){
			foreach($row as $f=>$v){
				if(isset($this->_autoincrement[$f]))
					if($v>$this->_autoincrement[$f])
					$this->_autoincrement[$f]=$v;
				$this->_data[$i][$f]=$v;
			}
		}
		parent::__construct();
	}


	public function index($filter = '', $start = '', $limit = '', $sort = '') {
		$data=$this->_data;
		if($filter!=''){
			$data=array();
			foreach($this->_data as $i=>$row){
				$selecionado=true;
				foreach($filter as $f=>$v)
				  if($row[$f]!=$v)
					$selecionado=false;
				if($selecionado)$data[]=$row;
			}
		}
		$result=array('success'=>true,'message'=>'Registros lidos com sucesso','total'=>count($this->_data),'data'=>$data);
		return $result;
	}

	public function get($id) {

	}

	public function post($params) {
		$row=array();
		foreach($this->_fields as $fld=>$field){
			if(empty($params[$field['name']])&&isset($this->_autoincrement[$field['name']])){
				$this->_autoincrement[$field['name']]++;
				$row[$field['name']]=$this->_autoincrement[$field['name']];
			}else{
				$row[$field['name']]=(isset($params[$field['name']])?$params[$field['name']]:'');
			}
		}
		$this->_data[]=$row;
		$result=array('success'=>true,'message'=>'Registro incluido com sucesso!','data'=>$row);
		return $result;
	}

	public function delete($id) {
		foreach($this->_data as $i=>$row)
			if($row['id']==$id)
			unset($this->_data[$i]);
		$result=array('success'=>true,'message'=>'Registro excluido com sucesso!','data'=>array());
		return $result;
	}

	public function put($id, $params) {
		$selecionado=null;
		foreach($this->_data as $i=>$row){
			if($row['id']==$id){
				$selecionado=$i;
				foreach($this->_fields as $fld=>$field){
					if(empty($params[$field['name']])&&isset($this->_autoincrement[$field['name']])){
						$this->_autoincrement[$field['name']]++;
						$this->_data[$i][$field['name']]=$this->_autoincrement[$field['name']];
					}else{
						$this->_data[$i][$field['name']]=(isset($params[$field['name']])?$params[$field['name']]:'');
					}
				}

			}
		}

		$result=array('success'=>true,'message'=>'Registro atualizado com sucesso!','data'=>($selecionado==null?array():$this->_data[$selecionado]));
	}

}
